package com.dolaw.exomediaplayer;
import android.app.Service;
import android.content.Intent;

import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private String TAG = MusicService.class.getName();
    private SimpleExoPlayer player;
    private Timer timer;
    private SimpleExoPlayer.EventListener eventListener = new SimpleExoPlayer.EventListener() {

        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
            Log.i(TAG,"onTracksChanged");
        }

        @Override
        public void onLoadingChanged(boolean isLoading) {
            Log.i(TAG,"onLoadingChanged");
        }

        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            Log.i(TAG,"onPlayerStateChanged: playWhenReady = "+String.valueOf(playWhenReady)
                    +" playbackState = "+playbackState);
            switch (playbackState){
                case SimpleExoPlayer.STATE_ENDED:
                    Log.i(TAG,"Playback ended!");
                    //Stop playback and return to start position
                    if (player!=null){
//                        player.release();//释放占用的资源
//                        deleteTimer(); //释放占时器
//                        player.seekTo(0);
//                        player.setPlayWhenReady(false);
                    }
                    break;
                case SimpleExoPlayer.STATE_READY:
                    Log.i(TAG,"ExoPlayer ready!");
                    break;
                case SimpleExoPlayer.STATE_BUFFERING:
                    Log.i(TAG,"Playback buffering!");
                    break;
                case SimpleExoPlayer.STATE_IDLE:
                    Log.i(TAG,"ExoPlayer idle!");
                    break;
            }
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            Log.i(TAG,"onPlaybackError: "+error.getMessage());
        }

    };

    public MusicService() {}
    @Override
    public  IBinder onBind(Intent intent){
        return new MusicControl();
    }
    @Override
    public void onCreate(){
        super.onCreate();
        //step1.创建轨道选择器实例
        DefaultTrackSelector trackSelector = new DefaultTrackSelector();
        //step2.创建本地缓存
        DefaultLoadControl loadControl =new DefaultLoadControl();
        //step3.创建播放器
        player = ExoPlayerFactory.newSimpleInstance(this,trackSelector,loadControl);//创建音乐播放器对象,exoPlayer实例
        //step4.添加监听
        player.addListener(eventListener);
        //step5.数据初始化
        initMediaSource();
        player.setThrowsWhenUsingWrongThread(false);
    }

    /**
     * 初始化播放资源
     */
    public void initMediaSource(){
        //  Uri uri=Uri.parse("android.resource://"+getPackageName()+"/raw/"+"music"+0+"mp3");
       // Uri uri = Uri.parse("https://storage.googleapis.com/exoplayer-test-media-0/play.mp3");
        //  Uri uri = Uri.parse("https://test.dolawing.com/sssb/SssbApp/sssbapp!downloadFileAjaxp.action?callId=0661b5588465ed1801846c1f6c080105");
        //100秒音频
        //Uri uri = Uri.parse("https://test.dolawing.com/sssb/SssbApp/sssbapp!downloadFileAjaxp.action?callId=0661b558847a524201847a7763f50005");
        //100秒音频
//        Uri uri = Uri.parse("https://test.dolawing.com/sssb/SssbApp/sssbapp!downloadFileAjaxp.action?callId=0661b558847a524201847a7763f50005");
        //1000秒 超长音频
        Uri uri = Uri.parse("https://test.dolawing.com/sssb/SssbApp/sssbapp!downloadFileAjaxp.action?callId=0661b5588479648a01847a4174ea0046");
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(
                this,
                Util.getUserAgent(this, "myExoPlayerDemo"));
        //创建普通 mediaSource
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(uri);
//        MediaSource mediaSource = new ExtractorMediaSource(uri,
//                new CacheDataSourceFactory(this, 100 * 1024 * 1024, 5 * 1024 * 1024),
//                new DefaultExtractorsFactory(), null, null);
        //准备播放
        player.prepare(mediaSource);
        //不播放
        player.setPlayWhenReady(false);
        //添加计时器
        addTimer();
    }

    public void addTimer(){ //添加计时器用于设置音乐播放器中的播放进度条
        if(timer==null){
            timer=new Timer();//创建计时器对象
            player.getApplicationLooper();
            TimerTask task=new TimerTask() {
                @Override
                public void run() {
                    if (player==null) return;
                    long duration=player.getDuration();//获取歌曲总时长
                    long currentPosition=player.getCurrentPosition();//获取播放进度
                    Message msg= MainActivity.handler.obtainMessage();//创建消息对象
                    //将音乐的总时长和播放进度封装至消息对象中
                    Bundle bundle=new Bundle();
                    bundle.putLong("duration",duration);
                    bundle.putLong("currentPosition",currentPosition);
                    msg.setData(bundle);
                    //将消息发送到主线程的消息队列
                    MainActivity.handler.sendMessage(msg);
                }
            };
            //开始计时任务后的5毫秒，第一次执行task任务，以后每500毫秒执行一次
            timer.schedule(task,5,500);
        }
    }

    public void deleteTimer(){  //取消计时器
        if(timer!=null){
            timer.cancel();
        }
    }

    class MusicControl extends Binder{//Binder是一种跨进程的通信方式
        public void play(){//String path
            //资源加载后立即播放
            player.setPlayWhenReady(true);

        }
        public void pausePlay(){
            player.setPlayWhenReady(false);//暂停播放音乐
        }
        public void continuePlay(){
            player.setPlayWhenReady(true);//继续播放音乐
        }
        public void seekTo(int progress){
            player.seekTo(progress);//设置音乐的播放位置
        }

        public boolean setPlaySpeed(float speed) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    //设置播放速度和音调均为2倍速
                    PlaybackParameters playParams = new PlaybackParameters(speed);
                    player.setPlaybackParameters(playParams);
                    return true;
                } catch (Exception e) {
                    Log.e("MediaPlayer倍速设置", "setPlaySpeed: ", e);
                    return false;
                }
            }
            return false;
        }
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.i(TAG,"执行onDestroy");
        if(player==null) return;
        if(player.isPlaying()) player.stop();//停止播放音乐
        player.release();//释放占用的资源
        player=null;//将player置为空
        deleteTimer(); //释放定时器
    }
}
